home *** CD-ROM | disk | FTP | other *** search
/ Enter 2006 September / Enter 09 2006.iso / Internet / SpamExperts Home 1.1 / SpamExperts Home.exe / lib / spamexperts.modules / email / Message.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2006-07-14  |  28.4 KB  |  858 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.4)
  3.  
  4. '''Basic message object for the email package object model.'''
  5. import re
  6. import uu
  7. import binascii
  8. import warnings
  9. from cStringIO import StringIO
  10. from email import Utils
  11. from email import Errors
  12. from email import Charset
  13. SEMISPACE = '; '
  14. paramre = re.compile('\\s*;\\s*')
  15. tspecials = re.compile('[ \\(\\)<>@,;:\\\\"/\\[\\]\\?=]')
  16.  
  17. def _formatparam(param, value = None, quote = True):
  18.     '''Convenience function to format and return a key=value pair.
  19.  
  20.     This will quote the value if needed or if quote is true.
  21.     '''
  22.     if value is not None and len(value) > 0:
  23.         if isinstance(value, tuple):
  24.             param += '*'
  25.             value = Utils.encode_rfc2231(value[2], value[0], value[1])
  26.         
  27.         if quote or tspecials.search(value):
  28.             return '%s="%s"' % (param, Utils.quote(value))
  29.         else:
  30.             return '%s=%s' % (param, value)
  31.     else:
  32.         return param
  33.  
  34.  
  35. def _parseparam(s):
  36.     plist = []
  37.     while s[:1] == ';':
  38.         s = s[1:]
  39.         end = s.find(';')
  40.         while end > 0 and s.count('"', 0, end) % 2:
  41.             end = s.find(';', end + 1)
  42.         if end < 0:
  43.             end = len(s)
  44.         
  45.         f = s[:end]
  46.         if '=' in f:
  47.             i = f.index('=')
  48.             f = f[:i].strip().lower() + '=' + f[i + 1:].strip()
  49.         
  50.         plist.append(f.strip())
  51.         s = s[end:]
  52.     return plist
  53.  
  54.  
  55. def _unquotevalue(value):
  56.     if isinstance(value, tuple):
  57.         return (value[0], value[1], Utils.unquote(value[2]))
  58.     else:
  59.         return Utils.unquote(value)
  60.  
  61.  
  62. class Message:
  63.     """Basic message object.
  64.  
  65.     A message object is defined as something that has a bunch of RFC 2822
  66.     headers and a payload.  It may optionally have an envelope header
  67.     (a.k.a. Unix-From or From_ header).  If the message is a container (i.e. a
  68.     multipart or a message/rfc822), then the payload is a list of Message
  69.     objects, otherwise it is a string.
  70.  
  71.     Message objects implement part of the `mapping' interface, which assumes
  72.     there is exactly one occurrance of the header per message.  Some headers
  73.     do in fact appear multiple times (e.g. Received) and for those headers,
  74.     you must use the explicit API to set or get all the headers.  Not all of
  75.     the mapping methods are implemented.
  76.     """
  77.     
  78.     def __init__(self):
  79.         self._headers = []
  80.         self._unixfrom = None
  81.         self._payload = None
  82.         self._charset = None
  83.         self.preamble = None
  84.         self.epilogue = None
  85.         self.defects = []
  86.         self._default_type = 'text/plain'
  87.  
  88.     
  89.     def __str__(self):
  90.         '''Return the entire formatted message as a string.
  91.         This includes the headers, body, and envelope header.
  92.         '''
  93.         return self.as_string(unixfrom = True)
  94.  
  95.     
  96.     def as_string(self, unixfrom = False):
  97.         '''Return the entire formatted message as a string.
  98.         Optional `unixfrom\' when True, means include the Unix From_ envelope
  99.         header.
  100.  
  101.         This is a convenience method and may not generate the message exactly
  102.         as you intend because by default it mangles lines that begin with
  103.         "From ".  For more flexibility, use the flatten() method of a
  104.         Generator instance.
  105.         '''
  106.         Generator = Generator
  107.         import email.Generator
  108.         fp = StringIO()
  109.         g = Generator(fp)
  110.         g.flatten(self, unixfrom = unixfrom)
  111.         return fp.getvalue()
  112.  
  113.     
  114.     def is_multipart(self):
  115.         '''Return True if the message consists of multiple parts.'''
  116.         return isinstance(self._payload, list)
  117.  
  118.     
  119.     def set_unixfrom(self, unixfrom):
  120.         self._unixfrom = unixfrom
  121.  
  122.     
  123.     def get_unixfrom(self):
  124.         return self._unixfrom
  125.  
  126.     
  127.     def attach(self, payload):
  128.         '''Add the given payload to the current payload.
  129.  
  130.         The current payload will always be a list of objects after this method
  131.         is called.  If you want to set the payload to a scalar object, use
  132.         set_payload() instead.
  133.         '''
  134.         if self._payload is None:
  135.             self._payload = [
  136.                 payload]
  137.         else:
  138.             self._payload.append(payload)
  139.  
  140.     
  141.     def get_payload(self, i = None, decode = False):
  142.         """Return a reference to the payload.
  143.  
  144.         The payload will either be a list object or a string.  If you mutate
  145.         the list object, you modify the message's payload in place.  Optional
  146.         i returns that index into the payload.
  147.  
  148.         Optional decode is a flag indicating whether the payload should be
  149.         decoded or not, according to the Content-Transfer-Encoding header
  150.         (default is False).
  151.  
  152.         When True and the message is not a multipart, the payload will be
  153.         decoded if this header's value is `quoted-printable' or `base64'.  If
  154.         some other encoding is used, or the header is missing, or if the
  155.         payload has bogus data (i.e. bogus base64 or uuencoded data), the
  156.         payload is returned as-is.
  157.  
  158.         If the message is a multipart and the decode flag is True, then None
  159.         is returned.
  160.         """
  161.         if i is None:
  162.             payload = self._payload
  163.         elif not isinstance(self._payload, list):
  164.             raise TypeError('Expected list, got %s' % type(self._payload))
  165.         else:
  166.             payload = self._payload[i]
  167.         if decode:
  168.             if self.is_multipart():
  169.                 return None
  170.             
  171.             cte = self.get('content-transfer-encoding', '').lower()
  172.             if cte == 'quoted-printable':
  173.                 return Utils._qdecode(payload)
  174.             elif cte == 'base64':
  175.                 
  176.                 try:
  177.                     return Utils._bdecode(payload)
  178.                 except binascii.Error:
  179.                     return payload
  180.                 except:
  181.                     None<EXCEPTION MATCH>binascii.Error
  182.                 
  183.  
  184.             None<EXCEPTION MATCH>binascii.Error
  185.             if cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'):
  186.                 sfp = StringIO()
  187.                 
  188.                 try:
  189.                     uu.decode(StringIO(payload + '\n'), sfp, quiet = True)
  190.                     payload = sfp.getvalue()
  191.                 except uu.Error:
  192.                     return payload
  193.                 except:
  194.                     None<EXCEPTION MATCH>uu.Error
  195.                 
  196.  
  197.             None<EXCEPTION MATCH>uu.Error
  198.         
  199.         return payload
  200.  
  201.     
  202.     def set_payload(self, payload, charset = None):
  203.         """Set the payload to the given value.
  204.  
  205.         Optional charset sets the message's default character set.  See
  206.         set_charset() for details.
  207.         """
  208.         self._payload = payload
  209.         if charset is not None:
  210.             self.set_charset(charset)
  211.         
  212.  
  213.     
  214.     def set_charset(self, charset):
  215.         '''Set the charset of the payload to a given character set.
  216.  
  217.         charset can be a Charset instance, a string naming a character set, or
  218.         None.  If it is a string it will be converted to a Charset instance.
  219.         If charset is None, the charset parameter will be removed from the
  220.         Content-Type field.  Anything else will generate a TypeError.
  221.  
  222.         The message will be assumed to be of type text/* encoded with
  223.         charset.input_charset.  It will be converted to charset.output_charset
  224.         and encoded properly, if needed, when generating the plain text
  225.         representation of the message.  MIME headers (MIME-Version,
  226.         Content-Type, Content-Transfer-Encoding) will be added as needed.
  227.  
  228.         '''
  229.         if charset is None:
  230.             self.del_param('charset')
  231.             self._charset = None
  232.             return None
  233.         
  234.         if isinstance(charset, str):
  235.             charset = Charset.Charset(charset)
  236.         
  237.         if not isinstance(charset, Charset.Charset):
  238.             raise TypeError(charset)
  239.         
  240.         self._charset = charset
  241.         if not self.has_key('MIME-Version'):
  242.             self.add_header('MIME-Version', '1.0')
  243.         
  244.         if not self.has_key('Content-Type'):
  245.             self.add_header('Content-Type', 'text/plain', charset = charset.get_output_charset())
  246.         else:
  247.             self.set_param('charset', charset.get_output_charset())
  248.         if str(charset) != charset.get_output_charset():
  249.             self._payload = charset.body_encode(self._payload)
  250.         
  251.         if not self.has_key('Content-Transfer-Encoding'):
  252.             cte = charset.get_body_encoding()
  253.             
  254.             try:
  255.                 cte(self)
  256.             except TypeError:
  257.                 self._payload = charset.body_encode(self._payload)
  258.                 self.add_header('Content-Transfer-Encoding', cte)
  259.             except:
  260.                 None<EXCEPTION MATCH>TypeError
  261.             
  262.  
  263.         None<EXCEPTION MATCH>TypeError
  264.  
  265.     
  266.     def get_charset(self):
  267.         """Return the Charset instance associated with the message's payload.
  268.         """
  269.         return self._charset
  270.  
  271.     
  272.     def __len__(self):
  273.         '''Return the total number of headers, including duplicates.'''
  274.         return len(self._headers)
  275.  
  276.     
  277.     def __getitem__(self, name):
  278.         '''Get a header value.
  279.  
  280.         Return None if the header is missing instead of raising an exception.
  281.  
  282.         Note that if the header appeared multiple times, exactly which
  283.         occurrance gets returned is undefined.  Use get_all() to get all
  284.         the values matching a header field name.
  285.         '''
  286.         return self.get(name)
  287.  
  288.     
  289.     def __setitem__(self, name, val):
  290.         '''Set the value of a header.
  291.  
  292.         Note: this does not overwrite an existing header with the same field
  293.         name.  Use __delitem__() first to delete any existing headers.
  294.         '''
  295.         self._headers.append((name, val))
  296.  
  297.     
  298.     def __delitem__(self, name):
  299.         '''Delete all occurrences of a header, if present.
  300.  
  301.         Does not raise an exception if the header is missing.
  302.         '''
  303.         name = name.lower()
  304.         newheaders = []
  305.         for k, v in self._headers:
  306.             if k.lower() != name:
  307.                 newheaders.append((k, v))
  308.                 continue
  309.         
  310.         self._headers = newheaders
  311.  
  312.     
  313.     def __contains__(self, name):
  314.         return [] in [ k.lower() for k, v in self._headers ]
  315.  
  316.     
  317.     def has_key(self, name):
  318.         '''Return true if the message contains the header.'''
  319.         missing = object()
  320.         return self.get(name, missing) is not missing
  321.  
  322.     
  323.     def keys(self):
  324.         """Return a list of all the message's header field names.
  325.  
  326.         These will be sorted in the order they appeared in the original
  327.         message, or were added to the message, and may contain duplicates.
  328.         Any fields deleted and re-inserted are always appended to the header
  329.         list.
  330.         """
  331.         return [ k for k, v in self._headers ]
  332.  
  333.     
  334.     def values(self):
  335.         """Return a list of all the message's header values.
  336.  
  337.         These will be sorted in the order they appeared in the original
  338.         message, or were added to the message, and may contain duplicates.
  339.         Any fields deleted and re-inserted are always appended to the header
  340.         list.
  341.         """
  342.         return [ v for k, v in self._headers ]
  343.  
  344.     
  345.     def items(self):
  346.         """Get all the message's header fields and values.
  347.  
  348.         These will be sorted in the order they appeared in the original
  349.         message, or were added to the message, and may contain duplicates.
  350.         Any fields deleted and re-inserted are always appended to the header
  351.         list.
  352.         """
  353.         return self._headers[:]
  354.  
  355.     
  356.     def get(self, name, failobj = None):
  357.         '''Get a header value.
  358.  
  359.         Like __getitem__() but return failobj instead of None when the field
  360.         is missing.
  361.         '''
  362.         name = name.lower()
  363.         for k, v in self._headers:
  364.             if k.lower() == name:
  365.                 return v
  366.                 continue
  367.         
  368.         return failobj
  369.  
  370.     
  371.     def get_all(self, name, failobj = None):
  372.         '''Return a list of all the values for the named field.
  373.  
  374.         These will be sorted in the order they appeared in the original
  375.         message, and may contain duplicates.  Any fields deleted and
  376.         re-inserted are always appended to the header list.
  377.  
  378.         If no such fields exist, failobj is returned (defaults to None).
  379.         '''
  380.         values = []
  381.         name = name.lower()
  382.         for k, v in self._headers:
  383.             if k.lower() == name:
  384.                 values.append(v)
  385.                 continue
  386.         
  387.         if not values:
  388.             return failobj
  389.         
  390.         return values
  391.  
  392.     
  393.     def add_header(self, _name, _value, **_params):
  394.         '''Extended header setting.
  395.  
  396.         name is the header field to add.  keyword arguments can be used to set
  397.         additional parameters for the header field, with underscores converted
  398.         to dashes.  Normally the parameter will be added as key="value" unless
  399.         value is None, in which case only the key will be added.
  400.  
  401.         Example:
  402.  
  403.         msg.add_header(\'content-disposition\', \'attachment\', filename=\'bud.gif\')
  404.         '''
  405.         parts = []
  406.         for k, v in _params.items():
  407.             if v is None:
  408.                 parts.append(k.replace('_', '-'))
  409.                 continue
  410.             parts.append(_formatparam(k.replace('_', '-'), v))
  411.         
  412.         if _value is not None:
  413.             parts.insert(0, _value)
  414.         
  415.         self._headers.append((_name, SEMISPACE.join(parts)))
  416.  
  417.     
  418.     def replace_header(self, _name, _value):
  419.         '''Replace a header.
  420.  
  421.         Replace the first matching header found in the message, retaining
  422.         header order and case.  If no matching header was found, a KeyError is
  423.         raised.
  424.         '''
  425.         _name = _name.lower()
  426.         for k, v in zip(range(len(self._headers)), self._headers):
  427.             if k.lower() == _name:
  428.                 self._headers[i] = (k, _value)
  429.                 break
  430.                 continue
  431.         else:
  432.             raise KeyError(_name)
  433.  
  434.     
  435.     def get_type(self, failobj = None):
  436.         """Returns the message's content type.
  437.  
  438.         The returned string is coerced to lowercase and returned as a single
  439.         string of the form `maintype/subtype'.  If there was no Content-Type
  440.         header in the message, failobj is returned (defaults to None).
  441.         """
  442.         warnings.warn('get_type() deprecated; use get_content_type()', DeprecationWarning, 2)
  443.         missing = object()
  444.         value = self.get('content-type', missing)
  445.         if value is missing:
  446.             return failobj
  447.         
  448.         return paramre.split(value)[0].lower().strip()
  449.  
  450.     
  451.     def get_main_type(self, failobj = None):
  452.         """Return the message's main content type if present."""
  453.         warnings.warn('get_main_type() deprecated; use get_content_maintype()', DeprecationWarning, 2)
  454.         missing = object()
  455.         ctype = self.get_type(missing)
  456.         if ctype is missing:
  457.             return failobj
  458.         
  459.         if ctype.count('/') != 1:
  460.             return failobj
  461.         
  462.         return ctype.split('/')[0]
  463.  
  464.     
  465.     def get_subtype(self, failobj = None):
  466.         """Return the message's content subtype if present."""
  467.         warnings.warn('get_subtype() deprecated; use get_content_subtype()', DeprecationWarning, 2)
  468.         missing = object()
  469.         ctype = self.get_type(missing)
  470.         if ctype is missing:
  471.             return failobj
  472.         
  473.         if ctype.count('/') != 1:
  474.             return failobj
  475.         
  476.         return ctype.split('/')[1]
  477.  
  478.     
  479.     def get_content_type(self):
  480.         """Return the message's content type.
  481.  
  482.         The returned string is coerced to lower case of the form
  483.         `maintype/subtype'.  If there was no Content-Type header in the
  484.         message, the default type as given by get_default_type() will be
  485.         returned.  Since according to RFC 2045, messages always have a default
  486.         type this will always return a value.
  487.  
  488.         RFC 2045 defines a message's default type to be text/plain unless it
  489.         appears inside a multipart/digest container, in which case it would be
  490.         message/rfc822.
  491.         """
  492.         missing = object()
  493.         value = self.get('content-type', missing)
  494.         if value is missing:
  495.             return self.get_default_type()
  496.         
  497.         ctype = paramre.split(value)[0].lower().strip()
  498.         if ctype.count('/') != 1:
  499.             return 'text/plain'
  500.         
  501.         return ctype
  502.  
  503.     
  504.     def get_content_maintype(self):
  505.         """Return the message's main content type.
  506.  
  507.         This is the `maintype' part of the string returned by
  508.         get_content_type().
  509.         """
  510.         ctype = self.get_content_type()
  511.         return ctype.split('/')[0]
  512.  
  513.     
  514.     def get_content_subtype(self):
  515.         """Returns the message's sub-content type.
  516.  
  517.         This is the `subtype' part of the string returned by
  518.         get_content_type().
  519.         """
  520.         ctype = self.get_content_type()
  521.         return ctype.split('/')[1]
  522.  
  523.     
  524.     def get_default_type(self):
  525.         """Return the `default' content type.
  526.  
  527.         Most messages have a default content type of text/plain, except for
  528.         messages that are subparts of multipart/digest containers.  Such
  529.         subparts have a default content type of message/rfc822.
  530.         """
  531.         return self._default_type
  532.  
  533.     
  534.     def set_default_type(self, ctype):
  535.         '''Set the `default\' content type.
  536.  
  537.         ctype should be either "text/plain" or "message/rfc822", although this
  538.         is not enforced.  The default content type is not stored in the
  539.         Content-Type header.
  540.         '''
  541.         self._default_type = ctype
  542.  
  543.     
  544.     def _get_params_preserve(self, failobj, header):
  545.         missing = object()
  546.         value = self.get(header, missing)
  547.         if value is missing:
  548.             return failobj
  549.         
  550.         params = []
  551.         for p in _parseparam(';' + value):
  552.             
  553.             try:
  554.                 (name, val) = p.split('=', 1)
  555.                 name = name.strip()
  556.                 val = val.strip()
  557.             except ValueError:
  558.                 name = p.strip()
  559.                 val = ''
  560.  
  561.             params.append((name, val))
  562.         
  563.         params = Utils.decode_params(params)
  564.         return params
  565.  
  566.     
  567.     def get_params(self, failobj = None, header = 'content-type', unquote = True):
  568.         """Return the message's Content-Type parameters, as a list.
  569.  
  570.         The elements of the returned list are 2-tuples of key/value pairs, as
  571.         split on the `=' sign.  The left hand side of the `=' is the key,
  572.         while the right hand side is the value.  If there is no `=' sign in
  573.         the parameter the value is the empty string.  The value is as
  574.         described in the get_param() method.
  575.  
  576.         Optional failobj is the object to return if there is no Content-Type
  577.         header.  Optional header is the header to search instead of
  578.         Content-Type.  If unquote is True, the value is unquoted.
  579.         """
  580.         missing = object()
  581.         params = self._get_params_preserve(missing, header)
  582.         if params is missing:
  583.             return failobj
  584.         
  585.  
  586.     
  587.     def get_param(self, param, failobj = None, header = 'content-type', unquote = True):
  588.         """Return the parameter value if found in the Content-Type header.
  589.  
  590.         Optional failobj is the object to return if there is no Content-Type
  591.         header, or the Content-Type header has no such parameter.  Optional
  592.         header is the header to search instead of Content-Type.
  593.  
  594.         Parameter keys are always compared case insensitively.  The return
  595.         value can either be a string, or a 3-tuple if the parameter was RFC
  596.         2231 encoded.  When it's a 3-tuple, the elements of the value are of
  597.         the form (CHARSET, LANGUAGE, VALUE).  Note that both CHARSET and
  598.         LANGUAGE can be None, in which case you should consider VALUE to be
  599.         encoded in the us-ascii charset.  You can usually ignore LANGUAGE.
  600.  
  601.         Your application should be prepared to deal with 3-tuple return
  602.         values, and can convert the parameter to a Unicode string like so:
  603.  
  604.             param = msg.get_param('foo')
  605.             if isinstance(param, tuple):
  606.                 param = unicode(param[2], param[0] or 'us-ascii')
  607.  
  608.         In any case, the parameter value (either the returned string, or the
  609.         VALUE item in the 3-tuple) is always unquoted, unless unquote is set
  610.         to False.
  611.         """
  612.         if not self.has_key(header):
  613.             return failobj
  614.         
  615.         for k, v in self._get_params_preserve(failobj, header):
  616.             if k.lower() == param.lower():
  617.                 if unquote:
  618.                     return _unquotevalue(v)
  619.                 else:
  620.                     return v
  621.             unquote
  622.         
  623.         return failobj
  624.  
  625.     
  626.     def set_param(self, param, value, header = 'Content-Type', requote = True, charset = None, language = ''):
  627.         '''Set a parameter in the Content-Type header.
  628.  
  629.         If the parameter already exists in the header, its value will be
  630.         replaced with the new value.
  631.  
  632.         If header is Content-Type and has not yet been defined for this
  633.         message, it will be set to "text/plain" and the new parameter and
  634.         value will be appended as per RFC 2045.
  635.  
  636.         An alternate header can specified in the header argument, and all
  637.         parameters will be quoted as necessary unless requote is False.
  638.  
  639.         If charset is specified, the parameter will be encoded according to RFC
  640.         2231.  Optional language specifies the RFC 2231 language, defaulting
  641.         to the empty string.  Both charset and language should be strings.
  642.         '''
  643.         if not isinstance(value, tuple) and charset:
  644.             value = (charset, language, value)
  645.         
  646.         if not self.has_key(header) and header.lower() == 'content-type':
  647.             ctype = 'text/plain'
  648.         else:
  649.             ctype = self.get(header)
  650.         if not self.get_param(param, header = header):
  651.             if not ctype:
  652.                 ctype = _formatparam(param, value, requote)
  653.             else:
  654.                 ctype = SEMISPACE.join([
  655.                     ctype,
  656.                     _formatparam(param, value, requote)])
  657.         else:
  658.             ctype = ''
  659.             for old_param, old_value in self.get_params(header = header, unquote = requote):
  660.                 append_param = ''
  661.                 if old_param.lower() == param.lower():
  662.                     append_param = _formatparam(param, value, requote)
  663.                 else:
  664.                     append_param = _formatparam(old_param, old_value, requote)
  665.                 if not ctype:
  666.                     ctype = append_param
  667.                     continue
  668.                 ctype = SEMISPACE.join([
  669.                     ctype,
  670.                     append_param])
  671.             
  672.         if ctype != self.get(header):
  673.             del self[header]
  674.             self[header] = ctype
  675.         
  676.  
  677.     
  678.     def del_param(self, param, header = 'content-type', requote = True):
  679.         '''Remove the given parameter completely from the Content-Type header.
  680.  
  681.         The header will be re-written in place without the parameter or its
  682.         value. All values will be quoted as necessary unless requote is
  683.         False.  Optional header specifies an alternative to the Content-Type
  684.         header.
  685.         '''
  686.         if not self.has_key(header):
  687.             return None
  688.         
  689.         new_ctype = ''
  690.         for p, v in self.get_params(header = header, unquote = requote):
  691.             if p.lower() != param.lower():
  692.                 if not new_ctype:
  693.                     new_ctype = _formatparam(p, v, requote)
  694.                 else:
  695.                     new_ctype = SEMISPACE.join([
  696.                         new_ctype,
  697.                         _formatparam(p, v, requote)])
  698.             new_ctype
  699.         
  700.         if new_ctype != self.get(header):
  701.             del self[header]
  702.             self[header] = new_ctype
  703.         
  704.  
  705.     
  706.     def set_type(self, type, header = 'Content-Type', requote = True):
  707.         '''Set the main type and subtype for the Content-Type header.
  708.  
  709.         type must be a string in the form "maintype/subtype", otherwise a
  710.         ValueError is raised.
  711.  
  712.         This method replaces the Content-Type header, keeping all the
  713.         parameters in place.  If requote is False, this leaves the existing
  714.         header\'s quoting as is.  Otherwise, the parameters will be quoted (the
  715.         default).
  716.  
  717.         An alternative header can be specified in the header argument.  When
  718.         the Content-Type header is set, we\'ll always also add a MIME-Version
  719.         header.
  720.         '''
  721.         if not type.count('/') == 1:
  722.             raise ValueError
  723.         
  724.         if header.lower() == 'content-type':
  725.             del self['mime-version']
  726.             self['MIME-Version'] = '1.0'
  727.         
  728.         if not self.has_key(header):
  729.             self[header] = type
  730.             return None
  731.         
  732.         params = self.get_params(header = header, unquote = requote)
  733.         del self[header]
  734.         self[header] = type
  735.         for p, v in params[1:]:
  736.             self.set_param(p, v, header, requote)
  737.         
  738.  
  739.     
  740.     def get_filename(self, failobj = None):
  741.         """Return the filename associated with the payload if present.
  742.  
  743.         The filename is extracted from the Content-Disposition header's
  744.         `filename' parameter, and it is unquoted.  If that header is missing
  745.         the `filename' parameter, this method falls back to looking for the
  746.         `name' parameter.
  747.         """
  748.         missing = object()
  749.         filename = self.get_param('filename', missing, 'content-disposition')
  750.         if filename is missing:
  751.             filename = self.get_param('name', missing, 'content-disposition')
  752.         
  753.         if filename is missing:
  754.             return failobj
  755.         
  756.         return Utils.collapse_rfc2231_value(filename).strip()
  757.  
  758.     
  759.     def get_boundary(self, failobj = None):
  760.         """Return the boundary associated with the payload if present.
  761.  
  762.         The boundary is extracted from the Content-Type header's `boundary'
  763.         parameter, and it is unquoted.
  764.         """
  765.         missing = object()
  766.         boundary = self.get_param('boundary', missing)
  767.         if boundary is missing:
  768.             return failobj
  769.         
  770.         return Utils.collapse_rfc2231_value(boundary).rstrip()
  771.  
  772.     
  773.     def set_boundary(self, boundary):
  774.         """Set the boundary parameter in Content-Type to 'boundary'.
  775.  
  776.         This is subtly different than deleting the Content-Type header and
  777.         adding a new one with a new boundary parameter via add_header().  The
  778.         main difference is that using the set_boundary() method preserves the
  779.         order of the Content-Type header in the original message.
  780.  
  781.         HeaderParseError is raised if the message has no Content-Type header.
  782.         """
  783.         missing = object()
  784.         params = self._get_params_preserve(missing, 'content-type')
  785.         if params is missing:
  786.             raise Errors.HeaderParseError, 'No Content-Type header found'
  787.         
  788.         newparams = []
  789.         foundp = False
  790.         for pk, pv in params:
  791.             if pk.lower() == 'boundary':
  792.                 newparams.append(('boundary', '"%s"' % boundary))
  793.                 foundp = True
  794.                 continue
  795.             newparams.append((pk, pv))
  796.         
  797.         if not foundp:
  798.             newparams.append(('boundary', '"%s"' % boundary))
  799.         
  800.         newheaders = []
  801.         for h, v in self._headers:
  802.             if h.lower() == 'content-type':
  803.                 parts = []
  804.                 for k, v in newparams:
  805.                     if v == '':
  806.                         parts.append(k)
  807.                         continue
  808.                     parts.append('%s=%s' % (k, v))
  809.                 
  810.                 newheaders.append((h, SEMISPACE.join(parts)))
  811.                 continue
  812.             newheaders.append((h, v))
  813.         
  814.         self._headers = newheaders
  815.  
  816.     
  817.     def get_content_charset(self, failobj = None):
  818.         '''Return the charset parameter of the Content-Type header.
  819.  
  820.         The returned string is always coerced to lower case.  If there is no
  821.         Content-Type header, or if that header has no charset parameter,
  822.         failobj is returned.
  823.         '''
  824.         missing = object()
  825.         charset = self.get_param('charset', missing)
  826.         if charset is missing:
  827.             return failobj
  828.         
  829.         if isinstance(charset, tuple):
  830.             if not charset[0]:
  831.                 pass
  832.             pcharset = 'us-ascii'
  833.             charset = unicode(charset[2], pcharset).encode('us-ascii')
  834.         
  835.         return charset.lower()
  836.  
  837.     
  838.     def get_charsets(self, failobj = None):
  839.         '''Return a list containing the charset(s) used in this message.
  840.  
  841.         The returned list of items describes the Content-Type headers\'
  842.         charset parameter for this message and all the subparts in its
  843.         payload.
  844.  
  845.         Each item will either be a string (the value of the charset parameter
  846.         in the Content-Type header of that part) or the value of the
  847.         \'failobj\' parameter (defaults to None), if the part does not have a
  848.         main MIME type of "text", or the charset is not defined.
  849.  
  850.         The list will contain one string for each part of the message, plus
  851.         one for the container message (i.e. self), so that a non-multipart
  852.         message will still return a list of length 1.
  853.         '''
  854.         return [ part.get_content_charset(failobj) for part in self.walk() ]
  855.  
  856.     from email.Iterators import walk
  857.  
  858.